import 'package:logger/logger.dart';

import '../models/user.dart';
import '../core/database_helper.dart';

/// 用户服务类
class UserService {
  final DatabaseHelper _dbHelper = DatabaseHelper();
  static final Logger _logger = Logger();

  /// 验证用户登录
  Future<User?> validateLogin(String username, String password) async {
    try {
      final db = await _dbHelper.database;
      
      // 添加调试日志
      _logger.d('🔍 开始验证登录: username=$username');
      
      // 先查询用户是否存在
      final userMaps = await db.query(
        'users',
        where: 'username = ? AND is_active = 1 AND is_deleted = 0',
        whereArgs: [username],
      );
      
      if (userMaps.isEmpty) {
        _logger.w('❌ 用户不存在或已被禁用: $username');
        return null;
      }
      
      final user = User.fromMap(userMaps.first);
      _logger.d('✅ 用户存在: ${user.username}, role=${user.role}');
      
      // 验证密码
      final passwordHash = DatabaseHelper.hashPassword(password);
      _logger.d('🔐 密码验证: 输入密码哈希=$passwordHash, 存储密码哈希=${user.passwordHash}');
      
      if (passwordHash != user.passwordHash) {
        _logger.w('❌ 密码不匹配: 用户=$username');
        return null;
      }
      
      _logger.i('✅ 登录验证成功: $username');
      
      // 更新最后登录时间
      await db.update(
        'users',
        {'last_login_time': DateTime.now().toIso8601String()},
        where: 'id = ?',
        whereArgs: [user.id],
      );

      return user;
    } catch (e) {
      _logger.e('❌ 登录验证失败: $e');
      return null;
    }
  }

  /// 获取所有用户
  Future<List<User>> getAllUsers() async {
    try {
      final db = await _dbHelper.database;
      final List<Map<String, dynamic>> maps = await db.query(
        'users',
        where: 'is_deleted = 0',
        orderBy: 'created_at DESC',
      );

      return List.generate(maps.length, (i) {
        return User.fromMap(maps[i]);
      });
    } catch (e) {
      _logger.e('获取用户列表失败: $e');
      return [];
    }
  }

  /// 根据ID获取用户
  Future<User?> getUserById(int id) async {
    try {
      final db = await _dbHelper.database;
      final List<Map<String, dynamic>> maps = await db.query(
        'users',
        where: 'id = ? AND is_deleted = 0',
        whereArgs: [id],
      );

      if (maps.isEmpty) {
        return null;
      }

      return User.fromMap(maps.first);
    } catch (e) {
      _logger.e('获取用户失败: $e');
      return null;
    }
  }

  /// 根据用户名获取用户
  Future<User?> getUserByUsername(String username) async {
    try {
      final db = await _dbHelper.database;
      final List<Map<String, dynamic>> maps = await db.query(
        'users',
        where: 'username = ? AND is_deleted = 0',
        whereArgs: [username],
      );

      if (maps.isEmpty) {
        return null;
      }

      return User.fromMap(maps.first);
    } catch (e) {
      _logger.e('获取用户失败: $e');
      return null;
    }
  }

  /// 创建用户
  Future<bool> createUser(User user) async {
    try {
      final db = await _dbHelper.database;
      
      // 检查用户名是否已存在
      final existingUser = await getUserByUsername(user.username);
      if (existingUser != null) {
        return false;
      }

      await db.insert('users', user.toMap());
      return true;
    } catch (e) {
      _logger.e('创建用户失败: $e');
      return false;
    }
  }

  /// 更新用户
  Future<bool> updateUser(User user) async {
    try {
      final db = await _dbHelper.database;
      
      // 检查用户是否存在
      final existingUser = await getUserById(user.id!);
      if (existingUser == null) {
        return false;
      }

      // 如果用户名被修改，检查新用户名是否已存在
      if (existingUser.username != user.username) {
        final userWithSameName = await getUserByUsername(user.username);
        if (userWithSameName != null) {
          return false;
        }
      }

      await db.update(
        'users',
        user.toMap(),
        where: 'id = ?',
        whereArgs: [user.id],
      );
      return true;
    } catch (e) {
      _logger.e('更新用户失败: $e');
      return false;
    }
  }

  /// 删除用户（软删除）
  Future<bool> deleteUser(int id) async {
    try {
      final db = await _dbHelper.database;
      
      // 检查用户是否存在
      final existingUser = await getUserById(id);
      if (existingUser == null) {
        return false;
      }

      // 不能删除管理员账号
      if (existingUser.isAdmin) {
        return false;
      }

      await db.update(
        'users',
        {
          'is_deleted': 1,
          'updated_at': DateTime.now().toIso8601String(),
        },
        where: 'id = ?',
        whereArgs: [id],
      );
      return true;
    } catch (e) {
      _logger.e('删除用户失败: $e');
      return false;
    }
  }

  /// 修改密码
  Future<bool> changePassword(int userId, String oldPassword, String newPassword) async {
    try {
      final db = await _dbHelper.database;
      
      // 获取用户信息
      final user = await getUserById(userId);
      if (user == null) {
        return false;
      }

      // 验证旧密码
      if (!DatabaseHelper.verifyPassword(oldPassword, user.passwordHash)) {
        return false;
      }

      // 更新密码
      await db.update(
        'users',
        {
          'password_hash': DatabaseHelper.hashPassword(newPassword),
          'updated_at': DateTime.now().toIso8601String(),
        },
        where: 'id = ?',
        whereArgs: [userId],
      );
      return true;
    } catch (e) {
      _logger.e('修改密码失败: $e');
      return false;
    }
  }

  /// 重置密码
  Future<bool> resetPassword(int userId, String newPassword) async {
    try {
      final db = await _dbHelper.database;
      
      // 检查用户是否存在
      final user = await getUserById(userId);
      if (user == null) {
        return false;
      }

      // 更新密码
      await db.update(
        'users',
        {
          'password_hash': DatabaseHelper.hashPassword(newPassword),
          'updated_at': DateTime.now().toIso8601String(),
        },
        where: 'id = ?',
        whereArgs: [userId],
      );
      return true;
    } catch (e) {
      _logger.e('重置密码失败: $e');
      return false;
    }
  }

  /// 启用/禁用用户
  Future<bool> toggleUserStatus(int userId) async {
    try {
      final db = await _dbHelper.database;
      
      // 获取用户信息
      final user = await getUserById(userId);
      if (user == null) {
        return false;
      }

      // 不能禁用管理员账号
      if (user.isAdmin) {
        return false;
      }

      await db.update(
        'users',
        {
          'is_active': user.isActive ? 0 : 1,
          'updated_at': DateTime.now().toIso8601String(),
        },
        where: 'id = ?',
        whereArgs: [userId],
      );
      return true;
    } catch (e) {
      _logger.e('切换用户状态失败: $e');
      return false;
    }
  }

  /// 搜索用户
  Future<List<User>> searchUsers(String keyword) async {
    try {
      final db = await _dbHelper.database;
      final List<Map<String, dynamic>> maps = await db.query(
        'users',
        where: 'is_deleted = 0 AND (username LIKE ? OR real_name LIKE ? OR email LIKE ?)',
        whereArgs: ['%$keyword%', '%$keyword%', '%$keyword%'],
        orderBy: 'created_at DESC',
      );

      return List.generate(maps.length, (i) {
        return User.fromMap(maps[i]);
      });
    } catch (e) {
      _logger.e('搜索用户失败: $e');
      return [];
    }
  }

  /// 获取用户统计信息
  Future<Map<String, int>> getUserStatistics() async {
    try {
      final db = await _dbHelper.database;
      
      // 总用户数
      final totalResult = await db.rawQuery(
        'SELECT COUNT(*) as count FROM users WHERE is_deleted = 0'
      );
      final total = totalResult.first['count'] as int;

      // 活跃用户数
      final activeResult = await db.rawQuery(
        'SELECT COUNT(*) as count FROM users WHERE is_active = 1 AND is_deleted = 0'
      );
      final active = activeResult.first['count'] as int;

      // 管理员数量
      final adminResult = await db.rawQuery(
        'SELECT COUNT(*) as count FROM users WHERE role = 2 AND is_deleted = 0'
      );
      final admin = adminResult.first['count'] as int;

      return {
        'total': total,
        'active': active,
        'admin': admin,
      };
    } catch (e) {
      _logger.e('获取用户统计失败: $e');
      return {'total': 0, 'active': 0, 'admin': 0};
    }
  }

  /// 验证用户数据
  static Map<String, String?> validateUserData({
    String? username,
    String? password,
    String? realName,
    String? email,
    String? phone,
    String? department,
    String? position,
  }) {
    return {
      'username': User.validateUsername(username),
      'password': User.validatePassword(password),
      'realName': User.validateRealName(realName),
      'email': User.validateEmail(email),
      'phone': User.validatePhone(phone),
      'department': User.validateDepartment(department),
      'position': User.validatePosition(position),
    };
  }
} 